const process = require('process')
const path = require('path')
const fs = require('fs')
const mkdirp = require('mkdirp')
const color = require('cli-color');
const config = require('./config')

/** 将内容写入对应路径中文件
 * @param 文件名 文件路径 模版
 **/
function writeContentToFile(name, path, template) {
    fs.writeFileSync(
        path,
        template,
        (error, data) => {
            if (error) {
                console.log(error);
                process.exit()
            }
            console.log(color.green(`${name} file create success !!!`));
        }
    )
}

/**
 * 生成文件
 **/
const generateFile = (options) => {

    if (typeof options !== 'object') {
        console.log(color.red('options must be a object !!!'))
        process.exit() // 结束进程，终止构建。
    }

    // 组装参数
    options = Object.assign({
        pageRoot: config.filePath.page,
        componentRoot: config.filePath.component,
        fileType: 'page',
        name: 'index'
    }, options)

    if (!options.pageRoot && !options.compomentRoot) {
        console.log(color.red('please specify the correct path'))
        process.exit()
    }

    switch (options.fileType) {
        case 'page':
            // 根据不同的htmlEngines选取不同模版
            let pageTemplate = ''
            if (options.htmlEngines === 'jade') {
                pageTemplate = require('./template/page/jade.js')
            } else if (options.htmlEngines === 'html') {
                pageTemplate = require('./template/page/html.js')
            }
            const pfilePath = path.resolve(options.pageRoot, options.name)
            fs.mkdirSync(pfilePath) // 创建文件目录
            const pagePath = path.resolve(pfilePath, options.name + '.vue')
            writeContentToFile(options.name, pagePath, pageTemplate(options)) // 同步写入文件
            break
        case 'component':
            // 根据不同的htmlEngines选取不同模版
            let componentTemplate = ''
            if (options.htmlEngines === 'jade') {
                componentTemplate = require('./template/component/jade.js')
            } else if (options.htmlEngines === 'html') {
                componentTemplate = require('./template/component/html.js')
            }
            const cfilePath = path.resolve(options.componentRoot, options.name)
            fs.mkdirSync(cfilePath)
            const componentPath = path.resolve(cfilePath, options.name + '.vue')
            writeContentToFile(options.name, componentPath, componentTemplate(options)) // 同步写入文件
            break
        default:
            console.log(color.red('file type that does not exist'));
    }
}

module.exports = {
    generateFile
}